﻿using Ldt.InformationUnit.Common;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.ConfigXmlLoad;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimizeConfigModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.CommonModule.PersonMerger
{
    /// <summary>
    /// 分人员要素合并基础处理
    /// </summary>
    public class ElementMergeBase
    {
        /// <summary>
        /// 上下文内容信息
        /// </summary>
        private DataContext DataContext { get; }
        ///<summary>
        /// 案由集合
        ///</summary> 
        private List<CaseCauseModel> CaseCausesList { get; }
        /// <summary>
        /// 实例化构造函数
        /// </summary>
        /// <param name="dataContextIn"></param>
        public ElementMergeBase(DataContext dataContextIn) 
        {
            DataContext = dataContextIn;
            CaseCausesList = DataContext.DataLayerAns.CaseCausesList;
        }
        /// <summary>
        /// 根据配置进行加载数据源数据
        /// </summary>
        /// <returns></returns>
        public Dictionary<Tuple<string, string>, List<ElementModel>> LoadDataSource(List<DataModel> AnalysisDataModleList,string Causeid)
        {
            Dictionary<Tuple<string, string>, List<ElementModel>> keySourceData = new Dictionary<Tuple<string, string>, List<ElementModel>>();

            //根据唯一ID获取所有的数据信息
            List<ElementModel> dataList = GetListElmentModel(AnalysisDataModleList,Causeid);//获取数据


            //进行读取数据源
            if (DataContext.DataLayerSys.optimizeFactConfig != null)
            {
                foreach (OptimizeFactData optimizeFactData in DataContext.DataLayerSys.optimizeFactConfig?.OptimizeFactDatas?.OptimizeFactDatas)
                {
                    ////当前文书在优选中代称
                    //optimizeFactData.ID; 
                    /////当前文书的编号
                    //optimizeFactData.Code;
                    List<ElementModel> listData = null;
                    if (optimizeFactData.OptimziechildSources.Count > 0)
                    {
                        //该判断主要是用于在要素优选中数据源配置存在子级选择数据源，例如法庭笔录
                        string[] numbersource = optimizeFactData.SourceNumber.Split('>');
                        foreach (string sour in numbersource)
                        {
                            var model = optimizeFactData.OptimziechildSources.FirstOrDefault(mo => mo.ID == sour);
                            var listsource = dataList.Where(mo => mo.CRE_SourceID.ToLower() == model.Code.ToLower()).ToList();
                            if (listsource != null && listsource.Count > 0)
                            {
                                int? number = listsource.Max(mo => mo.CRE_SourceNumber);
                                listData = listsource.Where(mo => mo.CRE_SourceNumber == number).ToList();
                                break;
                            }
                        }
                    }
                    else
                    {
                        listData = dataList.Where(mo => mo.CRE_SourceID.ToLower() == optimizeFactData.Code.ToLower()).ToList();
                        if (listData.Count > 0)
                        {
                            int? number = listData.Max(mo => mo.CRE_SourceNumber);
                            if (number != null)
                            {
                                listData = listData.Where(mo => mo.CRE_SourceNumber == number).ToList();
                            }
                        }

                    }

                    if (listData != null && listData.Count > 0)
                    {
                        listData = this.FilterPersonFact(listData,AnalysisDataModleList,Causeid);
                    }

                    //判断当前的文书编号是是否已经存在当前数据集合中
                    if (!keySourceData.Keys.Any(source => source.Item1.ToLower() == optimizeFactData.Code.ToLower() && source.Item2.ToLower() == optimizeFactData.ID.ToLower()) && listData != null && listData.Count > 0)
                        keySourceData.Add(new Tuple<string, string>(optimizeFactData.Code.ToLower(), optimizeFactData.ID), listData);
                }
            }
            return keySourceData;

        }

        /// <summary>
        /// 进行对人员要素数据过滤及修正
        /// </summary>
        /// <param name="listPersonData">原始的人员数据</param>
        /// <returns></returns>l
        private List<ElementModel> FilterPersonFact(List<ElementModel> listPersonData, List<DataModel> AnalysisDataModleList, string Causeid)
        {
            return GetListElmentModel(AnalysisDataModleList, Causeid);
        }
        /// <summary>
        /// 将数据源转换为实体
        /// </summary>
        /// <returns></returns>
        public List<ElementModel> GetListElmentModel(List<DataModel> AnalysisDataModleList, string Causeid)
        {
            List<DataModel> causeElementdataModelList = AnalysisDataModleList;
            if (causeElementdataModelList != null && causeElementdataModelList.FirstOrDefault(a => a.XmlPath.IndexOf("主张方") > -1) != null)
            {
                List<DataModel> dataModelsAissNodeList = causeElementdataModelList.Where(a => a.XmlPath.IndexOf("主张方") > -1).ToList();
                List<ElementModel> elementModelList = new List<ElementModel>();
                foreach (DataModel itemAdvocate in dataModelsAissNodeList)
                {
                    DataModel dataModelasisPrentNode = causeElementdataModelList.FirstOrDefault(a => a.ID == itemAdvocate.ParentId);
                    AttributeInfo itemNameDataModel = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称");
                    if (itemNameDataModel != null)
                    {
                        string name = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                        string suitid = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                        List<DataModel> regsModeList = this.SubordinateDataModelList(causeElementdataModelList, dataModelasisPrentNode);
                        SituationPlotData situationPlotData = new SituationPlotData() { dataContext = DataContext };
                        SituationPlotResultModel situationPlotResultModel = situationPlotData.ObtainSituationPlot(regsModeList);
                        List<DataModel> dataModelsCuaseList = DataContext.DataLayerOpt.SourdatModleList.Select(a =>  a.Clone()).ToList();

                        foreach (var crimeData in situationPlotResultModel.crimeDataModelList)
                        {
                            foreach (DataModel model in crimeData.dataModelList)
                            {
                                regsModeList.Remove(model);
                                DataModel cuaseModel = dataModelsCuaseList.FirstOrDefault(a => a.ID == model.ID);
                                if (cuaseModel!=null)
                                {
                                    dataModelsCuaseList.Remove(cuaseModel);
                                }
                            }
                        }
                        foreach (var relevantData in situationPlotResultModel.relevantDataModelList)
                        {
                            foreach (DataModel model in relevantData.dataModelList)
                            {
                                regsModeList.Remove(model);
                                DataModel cuaseModel = dataModelsCuaseList.FirstOrDefault(a => a.ID == model.ID);
                                if (cuaseModel != null)
                                {
                                    dataModelsCuaseList.Remove(cuaseModel);
                                }
                            }
                        }
                        
                        List<DataModel> dataModelReg = regsModeList.Select(item => item.Clone()).ToList();
                        DataModel dataModelRoot = DataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == dataModelasisPrentNode.ID);
                        if (dataModelRoot == null)
                        {
                            DataContext.InteractiveShow.LogShow("合并数据错误原因：父级ID查找不到" + JsonConvert.SerializeObject(dataModelasisPrentNode));
                        }
                        DataModel dataPrentRoot = DataContext.DataLayerOpt.SourdatModleList.FirstOrDefault(a => a.ID == dataModelRoot?.ParentId);
                        dataPrentRoot.XmlPath = "案由要素";
                        dataModelReg.Add(dataPrentRoot);
                        List<DataModel> cuaseModelList = new List<DataModel>();
                        XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = DataContext };
                        cuaseModelList=xmlUtilCommon.SubordinateDataModelList(dataModelsCuaseList, dataModelRoot);
                        cuaseModelList.Add(dataPrentRoot);
                        XmlDocument xmlDocument = XmlUtility.DataModelByXml(cuaseModelList, dataPrentRoot.ParentId);
                        ElementModel elementModel = new ElementModel();
                        if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(suitid))
                        {
                            elementModel.CRE_FactElementXml = xmlDocument.OuterXml;
                            if (itemAdvocate.XmlPath.IndexOf("诉请要素") > -1)
                            {
                                elementModel.CRE_FactType = 1;
                            }
                            else if (itemAdvocate.XmlPath.IndexOf("事实要素") > -1)
                            {
                                elementModel.CRE_FactType = 2;
                            }
                            else if (itemAdvocate.XmlPath.IndexOf("结果要素") > -1)
                            {
                                elementModel.CRE_FactType = 3;
                            }
                            elementModel.CRE_SourceID = DataContext.DataCommon.SourceCode;
                            elementModel.CRE_SourceNumber = 0;
                            elementModel.CRE_SuitDegreeID = suitid;
                            elementModel.CRE_SuitName = name;
                            elementModel.situationPlotResultModel = situationPlotResultModel;
                            elementModelList.Add(elementModel);
                        }
                    }
                }
                return elementModelList;
            }
            else
            {
                return new List<ElementModel>();
            }

        }
        /// <summary>
        /// 获取下级所有子节点
        /// </summary>
        /// <param name="dataModelList">数据源集合</param>
        /// <param name="dataModel">当前数据</param>
        /// <returns></returns>
        private List<DataModel> SubordinateDataModelList(List<DataModel> dataModelList, DataModel dataModel)
        {
            List<DataModel> dataList = new List<DataModel>();
            dataList.Add(dataModel);
            List<DataModel> datasModels = dataModelList.Where(a => a.ParentId == dataModel.ID && a.ID != dataModel.ID).ToList();
            foreach (DataModel model in datasModels)
            {
                List<DataModel> dataModelValueList = SubordinateDataModelList(dataModelList, model);
                dataList.AddRange(dataModelValueList);
            }
            return dataList;
        }
        /// <summary>
        /// 将合并后的分人员数据，根据要素类型获取要素内容
        /// </summary>
        /// <param name="data">分人员合并后的数据</param>
        /// <param name="facttype">要素类型</param>
        /// <returns></returns>
        public Dictionary<Tuple<string, string>, XmlNode> GetFactTypePersonxml(List<ElementModel> data, int facttype)
        {
            Dictionary<Tuple<string, string>, XmlNode> keyValues = new Dictionary<Tuple<string, string>, XmlNode>();
            //获取当前要取交集的数据集合
            List<ElementModel> listwheredata = data.Where(mo => mo.CRE_FactType == facttype).ToList();
            //分人员数据加载集合
            for (int i = 0; i < listwheredata.Count; i++)
            {
                //加载分人员数据
                Tuple<string, string> tuplekey = new Tuple<string, string>(listwheredata[i].CRE_SuitDegreeID, listwheredata[i].CRE_SuitName);
                XmlDocument xmlTemp = new XmlDocument();
                xmlTemp.LoadXml(listwheredata[i].CRE_FactElementXml);
                keyValues.Add(tuplekey, xmlTemp);
            }
            return keyValues;
        }
    }

    /// <summary>
    /// 获取分人员要素信息
    /// </summary>
    public class ElementModel
    {
        /// <summary>
        /// 要素类型
        /// </summary>
        public int CRE_FactType { get; set; }

        /// <summary>
        /// 诉讼地位
        /// </summary>

        public string CRE_SuitDegreeID { get; set; }

        /// <summary>
        /// 诉讼人员名称
        /// </summary>
        public string CRE_SuitName { get; set; }

        /// <summary>
        /// 要素信息
        /// </summary>
        public string CRE_FactElementXml { get; set; }

        /// <summary>
        /// 数据来源
        /// </summary>
        public string CRE_SourceID { get; set; }

        /// <summary>
        /// 数据源顺序
        /// </summary>
        public int CRE_SourceNumber { get; set; }

        /// <summary>
        /// 案由情形情节数据
        /// </summary>
        public SituationPlotResultModel situationPlotResultModel;
    }
}
